/* eslint-disable no-magic-numbers */
const plumber = require('gulp-plumber');
const ts = require('gulp-typescript');
const gulp = require('gulp');
const sourcemaps = require('gulp-sourcemaps');
const path = require('path');
const concat = require('gulp-concat');
const clean = require('gulp-clean');
const babel = require('gulp-babel');
const iife = require('gulp-iife');

gulp.task('default', ['rt', 'clean'], function () {
    return gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(ts(require('./tsconfig.json').compilerOptions))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('build'));
});

gulp.task('clean', function () {
    return gulp.src('build').pipe(clean());
});

gulp.task('cleanTest', function () {
    return gulp.src('testBuild').pipe(clean());
});

gulp.task('rt', ['clean'], function () {
    return gulp.src([
            'runtime/Types.ts',
            'runtime/utils.ts',
            'runtime/require.ts',
            'runtime/ZPack.ts',
            'runtime/Module.ts',
            'runtime/start.ts'
        ])
        .pipe(ts({
            'charset': 'utf-8',
            'strict': true,
            'alwaysStrict': false,
            'declaration': false,
            'removeComments': false,
            'experimentalDecorators': false,
            'preserveConstEnums': false,
            'sourceMap': false,
            'moduleResolution': 'node',
            'target': 'ESNext',
            'typeRoots': ['./node_modules/@types', './typings/modules']
        }))
        //.pipe(babel({
        //    presets: ['@babel/env']
        //}))
        .pipe(concat('ZPack.js'))
        .pipe(iife())
        .pipe(gulp.dest('build/rt'));
});

gulp.task('test', ['cleanTest'], function () {
    const {
        ZPack
    } = require('./build');
    return gulp.src('src/**/*.ts')
        .pipe(plumber())
        .pipe(ZPack({
            rootPath: path.join(__dirname, 'src'),
            assembly: 'modulesAllInOne',
            external: {
                typescript: 'ts'
            }
        }))
        .pipe(gulp.dest('testBuild'));
});